import 'package:bot_toast/bot_toast.dart';
import 'package:cave_flutter/network/whl_api.dart';
import 'package:cave_flutter/pages/cave/cave_detail/cave_detail_logic.dart';
import 'package:cave_flutter/pages/cave/cave_detail/model/cave_model.dart';
import 'package:cave_flutter/pages/cave/cave_setting/cave_admin_privileges/cave_admin_privileges_logic.dart';
import 'package:cave_flutter/pages/cave/cave_setting/cave_admin_privileges/cave_admin_privileges_model.dart';
import 'package:cave_flutter/pages/cave/cave_setting/cave_admin_privileges/cave_admin_privileges_view.dart';
import 'package:cave_flutter/pages/cave/cave_setting/cave_edit_nickname/cave_edit_nickname_view.dart';
import 'package:cave_flutter/pages/cave/cave_setting/cave_join_condition/cave_join_condition_logic.dart';
import 'package:cave_flutter/pages/cave/cave_setting/cave_join_condition/cave_join_condition_model.dart';
import 'package:cave_flutter/pages/cave/cave_setting/cave_join_condition/cave_join_condition_view.dart';
import 'package:cave_flutter/pages/cave/cave_setting/cave_manage_member/cave_manage_member_view.dart';
import 'package:cave_flutter/pages/cave/cave_setting/cave_master_per_detail_model.dart';
import 'package:cave_flutter/routes/whl_app_pages.dart';
import 'package:cave_flutter/utils/whl_avatar_utils.dart';
import 'package:cave_flutter/utils/whl_dialog_util.dart';
import 'package:cave_flutter/utils/whl_toast_utils.dart';
import 'package:get/get.dart';

class CaveSettingLogic extends GetxController {
  int caveId = 0;
  CaveModel? model;
  int caveRole = 0;
  String? filePath;
  CaveJoinConditionModel joinConditionModel = CaveJoinConditionModel();
  CaveMasterPerDetailModel masterPerDetailModel = CaveMasterPerDetailModel();
  CaveAdminPrivilegesModel adminPrivilegesModel = CaveAdminPrivilegesModel();

  @override
  void onInit() {
    super.onInit();
    var arguments = Get.arguments;
    if (arguments != null) {
      caveId = arguments['caveId'];
      model = arguments['model'];
    }

    joinConditionModel.caveId = caveId;
    masterPerDetailModel.caveId = caveId;
    adminPrivilegesModel.caveId = caveId;

    getCaveRole();
  }

  void getCaveRole() async {
    ResponseData responseData =
        await WhlApi.getRoleInCave.get({'caveId': caveId});

    if (responseData.isSuccess()) {
      if (responseData.data['isGuest'] == 1) {
        caveRole = 1;
      }

      if (responseData.data['isAdmin'] == 1) {
        // 管理员
        caveRole = 2;
        getMasterPerDetail();
      }

      if (responseData.data['isMaster'] == 1) {
        // 群主
        caveRole = 3;
        getJoinCondition(); // 请求完成后会再调用getMasterPerDetail
      }

      if (caveRole < 2) {
        update();
      }
    } else {
      MyToast.show(responseData.msg ?? '获取角色信息失败');
    }
  }

  void getJoinCondition() async {
    ResponseData responseData =
        await WhlApi.getCaveJoinCondition.get({'caveId': caveId});
    if (responseData.isSuccess()) {
      if (responseData.data != null) {
        joinConditionModel = CaveJoinConditionModel.fromJson(responseData.data);
      }
      getMasterPerDetail();
    } else {
      MyToast.show(responseData.msg ?? '获取加入条件信息失败');
    }
  }

  void getMasterPerDetail() async {
    ResponseData responseData =
        await WhlApi.getMasterPerDetail.get({'caveId': caveId});
    if (responseData.isSuccess()) {
      if (responseData.data != null) {
        masterPerDetailModel =
            CaveMasterPerDetailModel.fromJson(responseData.data);
      }
      getAdminPrivileges();
    } else {
      MyToast.show(responseData.msg ?? '获取群主设置信息失败');
    }
  }

  void getAdminPrivileges() async {
    ResponseData responseData =
        await WhlApi.getAdminPerDetail.get({'caveId': caveId});
    if (responseData.isSuccess()) {
      if (responseData.data != null) {
        adminPrivilegesModel =
            CaveAdminPrivilegesModel.fromJson(responseData.data);
      }
      update();
    } else {
      MyToast.show(responseData.msg ?? '获取群主设置信息失败');
    }
  }

  void saveCavePer(int type) async {
    var params = {"caveId": caveId};
    switch (type) {
      case 0:
        params["groupProhibit"] =
            masterPerDetailModel.groupProhibit == 1 ? 0 : 1;
        break;
      case 1:
        params["masterPost"] = masterPerDetailModel.masterPost == 1 ? 0 : 1;
        break;
      case 2:
        params["adminPost"] = masterPerDetailModel.adminPost == 1 ? 0 : 1;
        break;
      case 3:
        params["memberPost"] = masterPerDetailModel.memberPost == 1 ? 0 : 1;
        break;
      case 4:
        params["memberMoneyPost"] =
            masterPerDetailModel.memberMoneyPost == 1 ? 0 : 1;
        break;
      default:
        break;
    }

    ResponseData responseData = await WhlApi.saveCavePer.post(params);
    if (responseData.isSuccess()) {
      switch (type) {
        case 0:
          masterPerDetailModel.groupProhibit =
              masterPerDetailModel.groupProhibit == 1 ? 0 : 1;
          break;
        case 1:
          masterPerDetailModel.masterPost =
              masterPerDetailModel.masterPost == 1 ? 0 : 1;
          break;
        case 2:
          masterPerDetailModel.adminPost =
              masterPerDetailModel.adminPost == 1 ? 0 : 1;
          break;
        case 3:
          masterPerDetailModel.memberPost =
              masterPerDetailModel.memberPost == 1 ? 0 : 1;
          break;
        case 4:
          masterPerDetailModel.memberMoneyPost =
              masterPerDetailModel.memberMoneyPost == 1 ? 0 : 1;
          break;
        default:
          break;
      }
    } else {
      MyToast.show(responseData.msg ?? '获取群主设置信息失败');
    }
    update();
  }

  void goSetNotice() {
    Get.toNamed(Routes.caveSetNoticePage,
        arguments: {'caveId': caveId, 'model': model});
  }

  void goSetNickname() {
    Get.to(() => CaveEditNicknamePage(),
        arguments: {'caveId': caveId, 'model': model});
  }

  void selectPhoto() {
    AvatarUtils.onChoosePhoto(Get.context!, onSelectEnd: (path) {
      filePath = path;
      BotToast.showLoading();
    }, onSuccess: (url) {
      saveAvatar(url);
    });
  }

  void saveAvatar(String url) {
    WhlApi.applyCave.post({
      "id": caveId,
      "caveImg": url,
    }).then((value) {
      if (value.isSuccess()) {
        model?.caveImg = url;
        MyToast.show("Cave头像设置成功");
        final Cave_detailLogic detailLogic = Get.find<Cave_detailLogic>();
        detailLogic.update();
      } else {
        MyToast.show(value.msg ?? "Cave头像设置失败");
      }
      BotToast.closeAllLoading();
    });
  }

  void presentJoinConditionView() {
    Get.bottomSheet(CaveJoinConditionView(), isScrollControlled: true);
    final joinConditionLogic = Get.find<CaveJoinConditionLogic>();
    joinConditionLogic.reloadData(joinConditionModel);
  }

  void presentCaveAdminPrivilegesView() {
    Get.bottomSheet(CaveAdminPrivilegesView(), isScrollControlled: true);
    CaveAdminPrivilegesLogic logic = Get.find<CaveAdminPrivilegesLogic>();
    logic.reloadDate(adminPrivilegesModel);
  }

  void goManageMemberPage() {
    Get.to(() => CaveManageMemberPage(), arguments: {
      'caveId': caveId,
      'caveRole': caveRole,
      'adminPrivilegesModel': adminPrivilegesModel
    });
  }

  void disbandCave() {
    WhlDialogUtil.showConfirmDialog("",
        description: "确定解散当前Cave?",
        sureString: "确定",
        cancelString: "取消", sureAction: () {
      WhlApi.delCave.get({'cid': caveId}).then((value) {
        if (value.isSuccess()) {
          MyToast.show("解散Cave成功");
          Get.back();
        } else {
          MyToast.show(value.msg ?? "解散Cave失败");
        }
      });
    });
  }

  void exitCave() {
    WhlDialogUtil.showConfirmDialog("",
        description: "确定退出当前Cave?",
        sureString: "确定",
        cancelString: "取消", sureAction: () {
      WhlApi.exitCave.get({'id': caveId}).then((value) {
        if (value.isSuccess()) {
          MyToast.show("退出Cave成功");
          Get.back();
        } else {
          MyToast.show(value.msg ?? "退出Cave失败");
        }
      });
    });
  }
}
